<template>
  <div class="management">
    <div class="mains_contain">
      <div class="contant">
        <el-form :inline="true" label-position="left" :model="searchForm" size="small">
          <el-form-item label="租户">
            <el-select v-model="searchForm.tenantId" style="width:100%" clearable placeholder="请选择">
              <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="分组名称">
            <el-input v-model="searchForm.name" clearable placeholder="请输入分组名称" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search" size="mini" icon="el-icon-search">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onAdd" size="mini" icon="el-icon-plus" v-has="['groupList:add']">创建分组</el-button>
          </el-form-item>
        </el-form>
        <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" fit :max-height="maxHeight" border stripe size="mini" highlight-current-row
          :header-cell-style="{background:'#e5e5e5',color:'#000'}">
          <el-table-column prop="name" label="分组名称" align="center"/>
          <el-table-column prop="tenantTxt" label="租户名称" align="center"/>
          <el-table-column prop="remark" label="描述" align="center"/>
          <el-table-column prop="updateTime" label="修改时间" align="center"/>
          <el-table-column prop="createdUserId" label="创建人" align="center">
            <template slot-scope="{row}">
              {{row.createBy}}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center"/>
          <el-table-column label="操作" width="350" align="center">
            <template slot-scope="{row}">
              <el-button type="text" size="mini" @click="handleInfo(row)" icon='el-icon-view'>详情</el-button>
              <el-button type="text" size="mini" @click="handleEdit(row)" icon='el-icon-edit' v-has="['groupList:edit']">编辑</el-button>
              <el-button type="text" style="color:#F56C6C" size="mini" @click="onDel(row)" icon='el-icon-delete' v-has="['groupList:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="text-align:right">
          <pagination v-show="pagination.total>0" :limit.sync="pagination.pageSize" :page.sync="pagination.page" :total="pagination.total" @pagination="getPageList" />
        </div>
      </div>
    </div>
    <el-dialog :title="cirTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="100px" size="small" :rules="rules">
        <el-form-item label="租户" prop="tenantId">
          <el-select v-model="form.tenantId" style="width:100%" placeholder="请选择">
            <el-option :label="item.name" v-for="item in tenantList" :value="item.id" :key="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="form.name" clearable @input="changeName" />
        </el-form-item>
        <el-form-item label="描述" prop="body">
          <el-input type="textarea" rows="5" v-model="form.remark" clearable placeholder="长度不超过200字" maxlength="200" @input="changes" />
          <div style="text-align: right;"><span>{{ form.remark && form.remark.trim().length || 0   }}</span>/200</div>
        </el-form-item>
      </el-form>
      <div style="text-align:right">
        <el-button type="primary" @click="handleSave('form')" size="small">保存</el-button>
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as api from '@/api/link/deviceGroup'
import * as tenantApi from "@/api/sys/tenant";
// import { account } from "@/utils/validate"

export default {
  comments: {},
  props: {},
  data() {
    let account = /^[\u4e00-\u9fa5a-zA-Z-z0-9]+$/
    const validateName = (rule, value, callback) => {
      if (value == "" || !value) {
        callback(new Error("请输入名称"));
      } else {
        if (account.test(value)) {
          callback();
        } else {
          callback(new Error("用户名不能出现特殊字符"));
        }
      }
    };
    return {
      tenantList: [],
      searchForm: {
        searchTime: []
      },
      multipleSelection: [],
      tableData: [],
      pagination: {
        total: 1,
        page: 1,
        pageSize: 10
      },
      cirTitle: '新增分组',
      dialogVisible: false,
      rules: {
        name: [
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' },
          { required: true, trigger: "blur", validator: validateName },

        ],
        tenantId: [{ required: true, message: '必须选择租户', trigger: 'change' }],
      },
      form: {},
      username: localStorage.getItem("username")
    }
  },
  computed: {
    maxHeight() {
      var curHeight =
        window.innerHeight ||
        document.documentElement.clientHeight ||
        document.body.clientHeight
      return curHeight - 280
    }
  },
  created() {
    let query = this.$route.query
    if (query.pages) {
      this.pagination.page = Number(query.pages)
    }
    this.getPageList()
    this.getTenantList()

  },
  mounted() {

  },
  methods: {
    changes(val) {
      this.form.remark = val.replace(/\s+/g, "")
    },
    changeName(val) {
      this.form.name = val.replace(/\s+/g, "")
    },
    // 获取租户数据
    getTenantList() {
      tenantApi.queryIdNamePair().then(res => {
        this.tenantList = res.data
      })
    },
    // 复选框事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    getPageList() {
      this.search()
    },
    search() {
      const p = Object.assign(this.searchForm, { page: this.pagination.page, pageSize: this.pagination.pageSize })
      api.page(p).then(resp => {
        this.tableData = resp.data.list
        this.pagination = resp.data.pagination
        this.pagination.page = resp.data.pagination.current
      })
    },
    onAdd() {
      this.form = {}
      this.cirTitle = '新增分组'
      this.dialogVisible = true
    },
    onDel(row) {
      this.$confirm('此操作将永久删除该条数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteById(row.id).then(resp => {
          if (resp.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if ((this.pagination.total - 1) % this.pagination.pageSize == 0) {
              if (this.pagination.page > 1) {
                this.pagination.page = this.pagination.page - 1;
              }
            }
            this.search();
          }
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleInfo(row) {
      this.$router.push({
        path: "/groupDetails",
        query: { ...row, page: this.pagination.page }
      })
    },
    handleEdit(row) {
      this.cirTitle = '编辑分组'
      this.form = Object.assign({}, row)
      this.dialogVisible = true
    },
    handleSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var p = Object.assign(this.form)
          switch (this.cirTitle) {
            case '新增分组':
              api.save(p).then(resp => {
                if (resp.code == 500) {
                  this.$message({
                    type: 'error',
                    message: resp.message
                  });
                } else {
                  this.$message({
                    type: 'success',
                    message: '新增成功!'
                  });
                  this.dialogVisible = false
                  this.search();
                }
              });
              break;
            case '编辑分组':
              api.update(p).then(resp => {
                if (resp.code == 500) {
                  this.$message({
                    type: 'error',
                    message: resp.message
                  });
                } else {
                  this.$message({
                    type: 'success',
                    message: '编辑成功!'
                  });
                  this.dialogVisible = false
                  this.search();
                }
              });
              break;
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  },
}
</script>

<style scoped lang="scss">
.management {
  padding: 20px;

  .curHeader {
    position: relative;
    height: 40px;
    .searcherBox {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
}
</style>
